;
var Mod_dialog_detail = function (options) {
    var opts = $.extend({
        containor: "#J_dialog_detail",     //唯一的弹层模块ID
        commentContainor: ".J_secord_list",
        colsLeft: ".J_cols_l",
        colsRight: ".J_cols_r",
        btn: "#submitButton",
        input: "#articleCommentContent",
        ul: ".secord-media-list",
        needFlexSlider: false,
        photoUL: "#J_photo_slider",
        photoContent: "#J_photo_content",
        btn_l: "#J_btn_l",
        btn_r: "#J_btn_r",
        photoIndex: 0,
        countBox: "#J_photo_count",
        photoParent:".scroll-pane",
        photoBarParent:".scroll-bar-wrap",
        keyBoard:true
    }, options || {});
    var self = this;
    this.opts = opts;
    this.$Containor = $(opts.containor);
    this.$colsL = this.$Containor.find(self.opts.colsLeft);
    this.$colsR = this.$Containor.find(self.opts.colsRight);
    this.$secComment = this.$Containor.find(self.opts.commentContainor);
    this.$uList = this.$Containor.find(self.opts.ul);
    this.$photoUL=$(opts.photoUL);
    this.$photoParent=$(opts.photoParent);
    this.$photoBarParent=$(opts.photoBarParent);
    this.itemWidth = $(opts.photoUL).find("li").eq(0).outerWidth(true);
    this.$_btn = this.$Containor.find(self.opts.btn);
    this.$_input = this.$Containor.find(self.opts.input);
    this.photoIndex = opts.photoIndex;
    this.max = $(opts.photoUL).find("li").size();
    this.$_btnl = $(opts.btn_l);
    this.$_btnr = $(opts.btn_r);
    this.$_count = $(opts.countBox);
    //下标从0开始
    this.$_count.text((parseInt(this.photoIndex) + 1) + "/" + this.max);

    this._timer = null;
    this.winH = $(window).height();
    this._minCount = 4;
    this._firstCurrent=true;
}
Mod_dialog_detail.prototype = {
    setAutoHeight: function (completeCallback) {
        var $_colsL = this.$colsL;
        var self = this;
        var colsLH;
        var colsRH;
        var imgdefereds = [];
        var $_imgs = $_colsL.find(".J_content_img").find("img");
        if ($_imgs.size() > 0) {
            $_imgs.each(function () {
                var dfd = $.Deferred();
                $(this).bind('load',function () {
                    dfd.resolve();
                }).bind('error', function () {
                    });
                if (this.complete) setTimeout(function () {
                    dfd.resolve();
                }, 200);
                imgdefereds.push(dfd);
            });
            $.when.apply(null, imgdefereds).done(function () {
                self.$colsL.removeAttr("style");
                self.$colsR.removeAttr("style");
                colsLH = self.$colsL.outerHeight();
                colsRH = self.$colsR.outerHeight();
                if (colsRH < colsLH) {
                    self.$colsR.css("height", colsLH);
                } else {
                    //右侧大于左边的，设置scroll
                    var $_ul = self.$Containor.find(self.opts.ul);
                    $_ul.css({
                        "overflow-y": "scroll",
                        "height": colsLH - 250
                    });
                }
                if(completeCallback&& $.isFunction(completeCallback)){
                    completeCallback();
                };
            });
        } else {
            colsLH = self.$colsL.outerHeight();
            colsRH = self.$colsR.outerHeight();
            if (colsRH < colsLH) {
                self.$colsR.css("height", colsLH);
            } else {
                //右侧大于左边的，设置scroll
                var $_ul = self.$Containor.find(self.opts.ul);
                $_ul.css({
                    "overflow-y": "scroll",
                    "height": colsLH - 250
                });
            }
        }
    },
    _keyBoard:function(){
        var self=this;
        if(this.max<=1){
            return;
        }
        $(document).off("keyup.photoborad keypress.photoborad").on("keyup.photoborad",function(e){
            if(!$(self.opts.input).is(":focus")){
                if(e.keyCode==37){
                    $(self.opts.btn_l).trigger("click");
                }else if(e.keyCode==39){
                    $(self.opts.btn_r).trigger("click");
                }
            }
        });
    },
    feedback: function () {
        var $_comments = this.$secComment;
        $(document).on("mouseenter.feedback", "li",function () {
            var $_feedback = $(this).find(".media-item");
            $_feedback.show();
        }).on("mouseleave.feedback", ".modal .media-list li", function () {
                var $_feedback = $(this).find(".media-item");
                $_feedback.hide();
            });
    },
    btnStatus: function () {
        var self = this, $Containor = this.$Containor;
        var $_btn = this.$_btn, $_input = this.$_input;
        $(document).on("focus.feedback", ".area_full .input[data-placeholder='true']",function () {
            $_btn = self.$Containor.find(self.opts.btn);
            $_btn.removeAttr("disabled", true).removeClass("btn-gray-light").addClass("btn-red");
        }).on("blur.feedback", ".area_full .input[data-placeholder='true']", function () {
                var text = $(this).val();
                $_btn = self.$Containor.find(self.opts.btn);
                if (text == "" || text == "请输入评论") {
                    $_btn.attr("disabled", true).removeClass("btn-red").addClass("btn-gray-light");
                }
            });
    },
    oEvent: function () {
        this.setAutoHeight();
        this.feedback();
        this.btnStatus();
        //分支判断
        this.flexSlider();
        if(this.opts.keyBoard){
            this._keyBoard();
        }
    },
    _getContainerMax: function () {
        this.maxItemShow = Math.floor(this.$photoParent.outerWidth() / this.itemWidth);
        return this.maxItemShow;
    },
    flexSlider: function () {
        var self = this;
        var $Containor = $(self.opts.containor);
        var $_btnl = $Containor.find(self.opts.btn_l);
        var $_btnr = $Containor.find(self.opts.btn_r);
        var $_photoUL = $(this.opts.photoUL), $_photoContent = $(this.opts.photoContent), $_lis = $_photoUL.find("li");
        var maxShowItem = self._getContainerMax();
        if (self.max > maxShowItem) {
            $.ajax({
                url: "http://static.aceona.com/V3/assets/js/widgets/ui/minified/jquery.all.slider.min.js",
                dataType: "script",
                crossDomain: true,
                error:function(){
                   alert("error");
                },
                success: function () {
                    //scrollpane parts
                    var scrollPane = $(".scroll-pane"),
                        scrollContent = $(".scroll-content"),
                        $_lis = scrollContent.find("li"), num = $_lis.size(), $_allSmallImg = $_lis.find("img");
                    singleItemWidth = $_lis.eq(0).outerWidth(true);
                    scrollContent.css({
                        "width": $_lis.eq(0).outerWidth(true) * num
                    });
                    var viewPortWidth = scrollPane.outerWidth();
                    $_lis.each(function (index, item) {
                        var isCanView = false;
                        var pos = singleItemWidth + index * singleItemWidth;
                        if (pos <= viewPortWidth + 20) {
                            var $_img = $(this).find("img");
                            var smallUrl = $_img.data("smallSrc");
                            if (smallUrl != null) {
                                $_img.attr("src", smallUrl).removeAttr("data-small-src");
                            };
                        }
                    });
                    //build slider
                    var scrollbar = $(".scroll-bar").slider({
                        step: 0.01,
                        change: function (event, ui) {
                            var lazyImgs = $_allSmallImg.filter('[data-small-src]');
                                    var scrollDis = Math.round(ui.value / 100 * ( scrollPane.width() - scrollContent.width())), absDis = parseInt(Math.abs(scrollDis));
                                    var maxAreaDis=absDis+viewPortWidth,minAreaDis=absDis-singleItemWidth;
                                    if (scrollContent.width() > scrollPane.width()) {
                                        scrollContent.stop().animate({
                                            "margin-left": scrollDis + "px"
                                        }, "fast");

                                    } else {
                                        scrollContent.css("margin-left", 0);
                                    }
                                    if(self._firstCurrent&&maxShowItem<self.max){
                                        //多图情况
                                        //设置scrollContent
                                        lazyImgs.each(function (index, item) {
                                            var $_parentLi = $(item).closest("li");
                                            var _index = $_lis.index($_parentLi);
                                            var pos = _index * singleItemWidth;
                                            if (pos>minAreaDis&&pos<maxAreaDis){
                                                //到达视口了
                                                var smallSrc = $(this).data("smallSrc");
                                                $(this).attr("src", smallSrc).removeAttr("data-small-src");
                                            }
                                        });
                                        self._firstCurrent=false;
                                    }else{
                                        lazyImgs.each(function (index, item) {
                                            var $_parentLi = $(item).closest("li");
                                            var _index = $_lis.index($_parentLi);
                                            var pos = _index * singleItemWidth;
                                            if ((pos - absDis) < viewPortWidth) {
                                                //到达视口了
                                                var smallSrc = $(this).data("smallSrc");
                                                $(this).attr("src", smallSrc).removeAttr("data-small-src");
                                            }
                                        });
                                    }
                                    var vertical = scrollbar.find(".ui-icon-grip-dotted-vertical");
                                    if (ui.value > 90) {
                                        if (vertical.is(":visible")) {
                                            vertical.animate({
                                                "left": -45 + "px"
                                    });
                                }
                            } else {
                                vertical.animate({
                                    "left": 0
                                });
                            }
                        },
                        slide: function (event, ui) {
                            //设置其拖动滑动,优化性能
                            var self=this;lazyImgs = $_allSmallImg.filter('[data-small-src]');
                            var scrollDis = ui.value / 100 * ( scrollPane.width() - scrollContent.width()), absDis = parseInt(Math.abs(scrollDis));
                            //设置scrollContent
                            scrollContent.stop().animate({
                                "margin-left": scrollDis + "px"
                            }, "fast");
                            lazyImgs.each(function (index, item) {
                                var $_parentLi = $(item).closest("li");
                                var _index = $_lis.index($_parentLi);
                                var pos = _index * singleItemWidth;
                                if ((pos - absDis) < viewPortWidth) {
                                    //到达视口了
                                    var smallSrc = $(this).data("smallSrc");
                                    $(this).attr("src", smallSrc).removeAttr("data-small-src");
                                }
                            });
                        },
                        stop: function () {
                            var $_bar = $(".scroll-bar").find(".ui-slider-handle");
                            var $_dot = $_bar.find(".ui-icon");
                            if ($_bar.outerWidth() < 50) {
                                $_dot.show();
                            } else {
                                $_dot.hide();
                            }
                        },
                        animate: "fast"
                    });

                    //append icon to handle
                    var handleHelper = scrollbar.find(".ui-slider-handle")
                        .mousedown(function () {
                            scrollbar.width(handleHelper.width());
                        })
                        .mouseup(function () {
                            scrollbar.width("100%");
                        })
                        .append("<span class='ui-icon ui-icon-grip-dotted-vertical'></span>")
                        .wrap("<div class='ui-handle-helper-parent'></div>").parent();
                    //change overflow to hidden now that slider handles the scrolling
                    scrollPane.css("overflow", "hidden");

                    //size scrollbar and handle proportionally to scroll distance
                    function sizeScrollbar() {
                        var remainder = scrollContent.width() - scrollPane.width();
                        var proportion = remainder / scrollContent.width();
                        var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
                        scrollbar.find(".ui-slider-handle").css({
                            width: handleSize,
                            "margin-left": -handleSize / 2
                        });
                        handleHelper.width("").width(scrollbar.width() - handleSize);
                    }

                    //reset slider value based on scroll content position
                    function resetValue() {
                        var remainder = scrollPane.width() - scrollContent.width();
                        var leftVal = scrollContent.css("margin-left") === "auto" ? 0 :
                            parseInt(scrollContent.css("margin-left"));
                        var percentage = Math.round(leftVal / remainder * 100);
                        try{
                            scrollbar.slider("value", percentage);
                        }catch(e){
                        }
                    }

                    //if the slider is 100% and window gets larger, reveal content
                    function reflowContent() {
                        var showing = scrollContent.width() + parseInt(scrollContent.css("margin-left"), 10);
                        var gap = scrollPane.width() - showing;
                        if (gap > 0) {
                            scrollContent.css("margin-left", parseInt(scrollContent.css("margin-left"), 10) + gap);
                        }
                    }
                    //init scrollbar size
                    setTimeout(sizeScrollbar, 10);//safari wants a timeout

                    //实例化刚开始的相册
                    self._initCurrent();
                }
            });
        }else{
            //当前少图情况，直接设置
            self._initCurrent();
        }
        //设置其当前高亮
        $_photoUL.off("click.photobar").on("click.photobar", "li", function () {
            self.$colsL = self.$Containor.find(self.opts.colsLeft);
            self.$colsR = self.$Containor.find(self.opts.colsRight);

            self.$colsL.removeAttr("style");
            self.$colsR.removeAttr("style");

            var imgSrc = $(this).find("img").data("bigSrc");
            $_lis.removeClass("current");
            $(this).addClass("current");
            $_photoContent.find("img").attr("src", imgSrc);
            self.photoIndex = $_lis.index(this);
            var percentValue = (self.photoIndex / self.max) * 100;
            if (self.photoIndex == (self.max - 1)) {
                $_btnr.hide();
                $_btnl.show();
                percentValue = 100;
            }
            if (self.photoIndex == 0) {
                percentValue = 0;
                $_btnl.hide();
                $_btnr.show();
            }
            self.$_count.text(self.photoIndex + 1 + "/" + self.max);
            if (self.max > maxShowItem&& $.fn.slider) {
                try{
                    window.setTimeout(function(){
                       $(".scroll-bar").slider("value", percentValue);
                    },10);
                }catch(e){

                }
            }
        });
        //进行相册内容的左右展示
        self.playNext();
        self.playPrev();
    },
    playNext: function () {
        var self = this;
        var $Containor = this.$Containor;
        var $_btnl = $Containor.find(self.opts.btn_l);
        var $_btnr = $Containor.find(self.opts.btn_r);
        $(document).off("click.photonext").on("click.photonext", "#J_btn_r",function () {
            self.photoIndex++;
            if (self.photoIndex >= self.max) {
                $_btnr.hide();
                $_btnl.show();
                self.photoIndex = 0;
                self._playPhoto(self.photoIndex);
            } else {
                $_btnl.show();
                self._playPhoto(self.photoIndex);
            }
        });
    },
    playPrev: function () {
        var self = this;
        var $Containor = this.$Containor;
        var $_btnl = $Containor.find(self.opts.btn_l);
        var $_btnr = $Containor.find(self.opts.btn_r);
        $(document).off("click.photoprev").on("click.photoprev", "#J_btn_l",function () {
            self.photoIndex--;
            if (self.photoIndex < 0) {
                $_btnl.hide();
                $_btnr.show();
                self.photoIndex = self.max - 1;
                self._playPhoto(self.photoIndex);
                return false;
            } else {
                self._playPhoto(self.photoIndex);
            }
        });
    },
    _initCurrent: function () {
        var self = this;
        var $_photoUL = $(this.opts.photoUL);
        var $_lis = $_photoUL.find("li");
        var $_imgs= $_lis.find("img");
        var maxShowItem = self._getContainerMax();
        if(self.max<=maxShowItem){
            //啥也不干一下，直接替换
            $_imgs.each(function(){
                $(this).attr("src",$(this).data("smallSrc"));
            });
            self.$photoBarParent.hide();
        }else{
            //多图情况下才设置位置
            $_lis.each(function () {
                if ($(this).hasClass("current")) {
                    self.photoIndex = $(this).attr("index");
                    self._setSliderPosition(self.photoIndex);
                    return;
                }
                ;
            });
        }
    },
    _setSliderPosition: function (index) {
        var self = this;
        var percentValue = (index / self.max) * 100;
        var maxShowItem = self._getContainerMax();
        if (index == (self.max - 1)) {
            percentValue = 100;
        }
        if (index == 0) {
            percentValue = 0;
        }
        self.$_count.text((parseInt(index) + 1) + "/" + self.max);
        if($.fn.slider&&self.max>maxShowItem){
            try{
                $(".scroll-bar").slider("value", percentValue);
            }catch(e){
            }
        }
    },
    _playPhoto: function (index) {
        //index下标从0开始
        var $_photoUL = $(this.opts.photoUL),self=this;
        $_photoUL.find("li").eq(index).trigger("click");
        var percentValue = ((index + 1) / this.max) * 100;
        var maxShowItem = this._getContainerMax();
        if (index == 0) {
            percentValue = 0;
        }
        if (index == this.max) {
            percentValue = 100;
        }
        this.$_count.text(parseInt(index) + 1 + "/" + this.max);
        if (self.max > maxShowItem&& $.fn.slider) {
            try{
                $(".scroll-bar").slider("value", percentValue);
            }catch(e){
            }
        }
    },
    _btnPos: function () {
        var self = this;
        var $_btnl = this.$_btnl;
        var $_btnr = this.$_btnr;
    },
    init: function () {
        this.oEvent();
    }
}
//实例化操作
var completeCallback=function(){
    var $_btnl=$("#J_btn_l"),$_btnr=$("#J_btn_r"),$_photoContent=$("#J_photo_content"),imgContent={};
    imgContent._w=$_photoContent.outerWidth();
    imgContent._h=$_photoContent.outerHeight();
    //进行值设定
    $_btnr.css({
        "display":"block",
        "width":Math.floor(imgContent._w*0.5),
        "height":Math.floor(imgContent._h)
    });
    $_btnl.css({
        "display":"block",
        "width":Math.floor(imgContent._w*0.5),
        "height":Math.floor(imgContent._h)
    });
};
var mod_dialog_detail = new Mod_dialog_detail();
mod_dialog_detail.init();
//第一次实例化加载的缩略图片
mod_dialog_detail.setAutoHeight(completeCallback);
